<?php

require_once("../shared/connect.php");

define('LOCK_TIMEOUT', 30);

// delete all locks older than LOCK_TIMEOUT seconds
function clear_old_locks() {
	$sql = "DELETE FROM `lock` WHERE last_modified < ".(time() - LOCK_TIMEOUT);
	mysql_query($sql) or die(mysql_error());
}

clear_old_locks();

$check_locks = json_decode($_GET['check_locks']);

if (count($check_locks) > 1) { // WARNING: SPEED HACK
	die("I don't feel like checking for more than one lock. ");
}

$check_lock = $check_locks[0];

// read locks
// by the way, "lock" is a reserved word in MySQL. great idea naming the table "lock"
$sql = "SELECT * FROM `lock` WHERE count > 0 AND `lock`.`name` = '$check_lock->name' AND `lock`.`van` = '$check_lock->van'";
$query = mysql_query($sql) or die(mysql_error());

$num_rows = mysql_num_rows($query);
$lock_open = $num_rows == 0;

if ($lock_open) {
	if (!empty($_GET[name])) {
		$timestamp = time();
		$sql = "INSERT INTO `lock` (name, van, count, last_modified) VALUES ('$_GET[name]', '$_GET[van]', 1, '$timestamp')";
		$query = mysql_query($sql) or die(mysql_error());
		echo mysql_insert_id();
	} else {
		echo "0";
	}
} else {
	echo "Locked out: $num_rows";
}

?>